package com.hong.jarlauncher;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TabbedPane extends JTabbedPane {
    public TabbedPane() {
        setTabPlacement(JTabbedPane.LEFT);
        setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        addNewServiceTab();
    }

    public void addNewServiceTab() {
        String initialTitle = "新服务";

        ServiceTabController controller = new ServiceTabController(this);
        ServicePanel servicePanel = new ServicePanel(controller::updateTitle);
        controller.setServicePanel(servicePanel);

        JPanel tabPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
        tabPanel.setOpaque(false);
        JLabel tabLabel = new JLabel(initialTitle);
        tabPanel.add(tabLabel);

        JButton closeButton = createCloseButton(servicePanel);
        tabPanel.add(closeButton);

        addTab(initialTitle, servicePanel);
        setTabComponentAt(getTabCount() - 1, tabPanel);
    }

    private static class ServiceTabController {
        private final TabbedPane tabbedPane;
        private ServicePanel servicePanel;

        public ServiceTabController(TabbedPane tabbedPane) {
            this.tabbedPane = tabbedPane;
        }

        public void setServicePanel(ServicePanel servicePanel) {
            this.servicePanel = servicePanel;
        }

        public void updateTitle(String serviceName) {
            int index = tabbedPane.indexOfComponent(servicePanel);
            if (index != -1) {
                String title = serviceName == null || serviceName.isEmpty() ? "未命名服务" : serviceName;
                tabbedPane.setTitleAt(index, title);
                tabbedPane.getTabComponentAt(index).revalidate();
                tabbedPane.getTabComponentAt(index).repaint();
            }
        }
    }

    private JButton createCloseButton(ServicePanel servicePanel) {
        JButton closeButton = new JButton("×");
        closeButton.setBorderPainted(false);
        closeButton.setContentAreaFilled(false);
        closeButton.setFocusPainted(false);
        closeButton.setMargin(new Insets(0, 5, 0, 0));
        closeButton.addActionListener(e -> {
            int index = indexOfComponent(servicePanel);
            if (index != -1) {
                servicePanel.stopService();
                remove(index);
            }
        });
        return closeButton;
    }

    public void setTitleAt(int index, String title) {
        Component tabComponent = getTabComponentAt(index);
        if (tabComponent instanceof JPanel) {
            JPanel panel = (JPanel) tabComponent;
            for (Component comp : panel.getComponents()) {
                if (comp instanceof JLabel) {
                    ((JLabel) comp).setText(title);
                    break;
                }
            }
        }
    }
}